package com.example.democlient;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.baidu.mapapi.Projection;
import com.example.democlient.model.Address;
import com.example.democlient.network.SocketService;
import com.example.democlient.network.serverpackets.SM_ADDRESS_QUERY_REQUEST;

@SuppressLint("HandlerLeak")
public class MapLocationActivity extends MapActivity implements OnClickListener,MKSearchListener {
	
	private  ImageButton imgBtn;
	private  ImageButton currentPositionBtn;
	private MapView mapView;  
    private MapController mapController;  
    private MKSearch myMKSearch;
    private GeoPoint centerPoint;
    private GeoPoint point1;
    private int locTypeFlag = 0;
    private double selfXAxis;
    private double selfYAxis;
    //private int districtId;
    private String addressName;
    //private int addressId;
    MyApplication app;
    String[] arrayAddress;
    boolean mapMove = false;
    //private int selfLoc = 0;
    
    private LocationListener locationListener = new LocationListener() {

		@Override
		public void onLocationChanged(Location arg0) {
			app.mBMapMan.getLocationManager().removeUpdates(locationListener);
			selfXAxis = arg0.getLatitude();
			selfYAxis = arg0.getLongitude();
            Double geolat = arg0.getLatitude() * 1E6;  
            Double geoLng = arg0.getLongitude() * 1E6;  
            GeoPoint mypoint = new GeoPoint(geolat.intValue(), geoLng.intValue());  
            myMKSearch = new MKSearch(); 
 	        myMKSearch.init(app.mBMapMan,MapLocationActivity.this);
			myMKSearch.reverseGeocode(mypoint); //逆地址解析
		}  
    	
    };
    
	Handler mainHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 1:  
            	//addressId = Integer.valueOf(String.valueOf(msg.obj));
            break;  
            case 2:  
            	@SuppressWarnings("unchecked")
				final List<Address> address = (List<Address>)msg.obj;
            	
            	if(address!=null&&address.size()>0){
            		if(address.size()==1&&address.get(0).getAddress().equals(addressName)){
            			 Address temp = address.get(0);
            			 point1 = new GeoPoint((int) (temp.getXaxis()* 1E6), (int) (temp.getYaxis()* 1E6));
	       	    		 mapView.getController().animateTo(point1);					
	       	    		 Drawable marker = getResources().getDrawable(R.drawable.maker1);//得到需要标在地图上的资源
	       	    		 marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());//为maker定义位置和边界
	       	    		 mapView.getOverlays().clear();
	       	    	     CustomItemizedOverlay overlay = new CustomItemizedOverlay(marker, MapLocationActivity.this); 
	       	    		 mapView.getOverlays().add(overlay);
	       	    	     OverlayItem overlayItem = new OverlayItem(point1, "", "");  
	       	    	     overlay.addOverlay(overlayItem);            			
            		}else{
                		arrayAddress = new String[address.size()];
                		for(int i=0;i<address.size();i++){
                		   arrayAddress[i] = address.get(i).getAddress();
                		}
                		Dialog dialog = new AlertDialog.Builder(MapLocationActivity.this)
                	    .setTitle("请选择地址")
                	    .setItems(arrayAddress, new DialogInterface.OnClickListener() { 
                	         public void onClick(DialogInterface dialog, int which) {
                	        	 Address temp = address.get(which);
                	        	 Toast.makeText(MapLocationActivity.this, arrayAddress[which], Toast.LENGTH_SHORT).show();
                	        	 point1 = new GeoPoint((int) (temp.getXaxis()* 1E6), (int) (temp.getYaxis()* 1E6));
                	    		 mapView.getController().animateTo(point1);					
                	    		 Drawable marker = getResources().getDrawable(R.drawable.maker1);//得到需要标在地图上的资源
                	    		 marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());//为maker定义位置和边界
                	    		 mapView.getOverlays().clear();
                	    	     CustomItemizedOverlay overlay = new CustomItemizedOverlay(marker, MapLocationActivity.this); 
                	    		 mapView.getOverlays().add(overlay);
                	    	     OverlayItem overlayItem = new OverlayItem(point1, "", "");  
                	    	     overlay.addOverlay(overlayItem);
                	         }
                	     }).create();
                	     dialog.show();             			
            		}
            	}else{
            	    myMKSearch = new MKSearch(); 
            	    myMKSearch.init(app.mBMapMan,MapLocationActivity.this);
            	    myMKSearch.geocode(addressName, "大连市");//地址解析
            	}
            break;            
            default:  
            
            break;  
            }  
            super.handleMessage(msg);  
        }  
    };  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_location);
		
		Intent _intent = getIntent();
		addressName = _intent.getStringExtra("name");
		//districtId = _intent.getIntExtra("districtId",0);
		
		imgBtn = (ImageButton)findViewById(R.id.commitBtn);
		imgBtn.setOnClickListener(this);
		currentPositionBtn = (ImageButton)findViewById(R.id.currentPosition);
		currentPositionBtn.setOnClickListener(this);
		app = (MyApplication)this.getApplication();
		app.mBMapMan.start();
        super.initMapActivity(app.mBMapMan);
        
        mapView = (MapView)findViewById(R.id.bmapView);
       
        mapView.setBuiltInZoomControls(false); 
        // 添加定位图层
        MyLocationOverlay mylocTest = new MyLocationOverlay(this, mapView);
        mylocTest.enableMyLocation(); // 启用定位
        mylocTest.enableCompass();    // 启用指南针
        mapView.getOverlays().add(mylocTest);
        
        
        mapController = mapView.getController();  
        // 设置地图的中心   
        centerPoint = new GeoPoint((int) (38.919341* 1E6), (int) (121.621385* 1E6)); 
        mapController.setCenter(centerPoint);  
        // 设置地图默认的缩放级别   
        mapController.setZoom(14);
        
        app = (MyApplication)this.getApplication();
        app.addActivity(this);
        app.setHandler(this.getClass(),mainHandler);
        
        if(addressName!=null&&addressName.length()>0){
    	    if(SocketService.getInstance().sendPacket(new SM_ADDRESS_QUERY_REQUEST(addressName), app)){
    		}
        }
  
       mapView.setOnTouchListener(new OnTouchListener() {

  		@Override
		public boolean onTouch(View v, MotionEvent event) {
  			
  			if(event.getAction() == MotionEvent.ACTION_DOWN){
  				mapMove = false;
  			}
  			if(event.getAction() == MotionEvent.ACTION_MOVE){
  				mapMove = true;
  			}
  			
			if(mapMove!=true && event.getAction()==MotionEvent.ACTION_UP){
				 //获得屏幕点击的位置	         
				 int x = (int)event.getX();	         
				 int y = (int)event.getY();	       
				 //将像素坐标转为地址坐标	         
				 GeoPoint pt = mapView.getProjection().fromPixels(x,y);	   
				 if(pt!=null){
			 	       myMKSearch = new MKSearch(); 
            	       myMKSearch.init(app.mBMapMan,MapLocationActivity.this);
					   myMKSearch.reverseGeocode(pt); 
				 }
				 //Toast.makeText(MapLocationActivity.this, "Test:"+pt.getLatitudeE6()+":"+pt.getLongitudeE6(), Toast.LENGTH_SHORT).show();
				 return false;
			}else{
				return false;
			}
		}

	});
	    
       // myMKSearch = new MKSearch(); 
       // myMKSearch.init(app.mBMapMan,this);
       // myMKSearch.geocode(addressName, "大连市");//地址解析
       // app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
	}
	@Override
	public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) {

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.commitBtn ){
			app.mBMapMan.getLocationManager().removeUpdates(locationListener);
			if(locTypeFlag == 1){
				Intent _intent = new Intent();
				_intent.putExtra("locTypeFlag", locTypeFlag);
				_intent.putExtra("addressName", addressName);
				_intent.putExtra("positionx", selfXAxis);
				_intent.putExtra("positiony", selfYAxis);
				setResult(CONTEXT_RESTRICTED, _intent);
				finish();
			}else{
				Intent _intent = new Intent();
				_intent.putExtra("addressName", addressName);
				_intent.putExtra("locTypeFlag", locTypeFlag);
				_intent.putExtra("positionx", point1.getLatitudeE6()/1E6);
				_intent.putExtra("positiony", point1.getLongitudeE6()/1E6);
				setResult(CONTEXT_RESTRICTED, _intent);
				finish();
			}
		}else if(v.getId()==R.id.currentPosition ){
			 locTypeFlag = 1;
			 // 不需要时移除监听
			 app.mBMapMan.getLocationManager().removeUpdates(locationListener);
			 // 注册监听
			 app.mBMapMan.getLocationManager().requestLocationUpdates(locationListener);
			
			 mapView.getController().animateTo(new GeoPoint((int) (selfXAxis* 1E6), (int) (selfYAxis* 1E6)));					
			 Drawable marker = getResources().getDrawable(R.drawable.maker1);//得到需要标在地图上的资源
			 marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());//为maker定义位置和边界
			 mapView.getOverlays().clear();
		     CustomItemizedOverlay overlay = new CustomItemizedOverlay(marker, this); 
			 mapView.getOverlays().add(overlay);
		     OverlayItem overlayItem = new OverlayItem(new GeoPoint((int) (selfXAxis* 1E6), (int) (selfYAxis* 1E6)), "", "");  
		     overlay.addOverlay(overlayItem);
			
		}
		
	}

	@Override
	public void onGetAddrResult(MKAddrInfo res, int error) {
		 if (error != 0) {
			  //String str = String.format("错误号：%d", error);
			  //Toast.makeText(MapLocationActivity.this, str, Toast.LENGTH_LONG).show();
			 //myMKSearch.suggestionSearch(addressName); 
			 return;
		 }
		 mapView.getController().animateTo(res.geoPt);					
		 String strInfo = String.format("纬度：%f 经度：%f\r\n", res.geoPt.getLatitudeE6()/1e6,res.geoPt.getLongitudeE6()/1e6);
		 Toast.makeText(MapLocationActivity.this, strInfo, Toast.LENGTH_LONG).show();
		 Drawable marker = getResources().getDrawable(R.drawable.maker1);//得到需要标在地图上的资源
		 marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());//为maker定义位置和边界
		 mapView.getOverlays().clear();
	     CustomItemizedOverlay overlay = new CustomItemizedOverlay(marker, this); 
		 mapView.getOverlays().add(overlay);
	     point1 = new GeoPoint((int) ( res.geoPt.getLatitudeE6()), (int) (res.geoPt.getLongitudeE6()));  
	     OverlayItem overlayItem = new OverlayItem(point1, "", "");  
	     overlay.addOverlay(overlayItem);
	     
	    // if(this.locTypeFlag==1){
	     if(res.addressComponents!=null){
	    	addressName = res.addressComponents.street;
	    //	 }
	     }
	}

	@Override
	public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onGetPoiResult(MKPoiResult res, int type, int error) {

	}

	@Override
	public void onGetRGCShareUrlResult(String arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onGetSuggestionResult(MKSuggestionResult res, int iError) {
	        if (iError!= 0 || res == null) {
	          Toast.makeText(MapLocationActivity.this, "抱歉，未找到结果", Toast.LENGTH_LONG).show();
	          return;
	        }
	        int nSize = res.getSuggestionNum();
	        String[] mStrSuggestions = new String[nSize];
	        for (int i = 0; i < nSize; i++)
	        {
	            mStrSuggestions[i] = res.getSuggestion(i).city + res.getSuggestion(i).key;
	        }
		
	}

	@Override
	public void onGetTransitRouteResult(MKTransitRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onGetWalkingRouteResult(MKWalkingRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {  
		    private ArrayList<OverlayItem> overlayItemList = new ArrayList<OverlayItem>();  
		    @SuppressWarnings("unused")
			private Context context;  
		  
		    public CustomItemizedOverlay(Drawable defaultMarker) {  
		        super(boundCenterBottom(defaultMarker));  
		    }  
		  
		    public CustomItemizedOverlay(Drawable marker, Context context) {  
		        super(boundCenterBottom(marker));  
		        this.context = context;  
		    }

		    @Override  
		    public int size() {  
		        return overlayItemList.size();  
		    }  
		  
		    public void addOverlay(OverlayItem overlayItem) {  
		        overlayItemList.add(overlayItem);  
		        this.populate();  
		    }  
		    @Override  
		    public void draw(Canvas canvas, MapView mapView, boolean shadow) {  
		        super.draw(canvas, mapView, shadow);  
		        //Projection接口用于屏幕像素点坐标系统和地球表面经纬度点坐标系统之间的变换   
		        Projection projection = mapView.getProjection();  
		        //遍历所有的OverlayItem   
		        for (int index = this.size() - 1; index >= 0; index--) {  
		            //得到给定索引的item   
		            OverlayItem overLayItem = getItem(index);  
		  
		            //把经纬度变换到相对于MapView左上角的屏幕像素坐标   
		            Point point = projection.toPixels(overLayItem.getPoint(), null);  
		  
		            Paint paintText = new Paint();  
		            paintText.setColor(Color.RED);  
		            paintText.setTextSize(13);  
		            //绘制文本   
		            canvas.drawText(overLayItem.getTitle(), point.x + 10, point.y - 15, paintText);  
		        }  

		    }
		    @Override  
		    //处理点击事件  
		    protected boolean onTap(int i) {  
		        setFocus(overlayItemList.get(i));  
		        return true;  
		    }  
			@Override
			protected OverlayItem createItem(int i) {
				 return overlayItemList.get(i);  
			}
	   }
	   
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        getMenuInflater().inflate(R.menu.activity_main, menu);
	        return true;
	    }
	    public boolean onOptionsItemSelected(MenuItem item){
	    	super.onOptionsItemSelected(item);
	    	if(item.getItemId()==R.id.menu_settings){
	    		app.exit();
	    	}
			return true;
	    }
}
